package cn.stylefeng.guns.modular.demo.excel.listener.aslikang;

import cn.hutool.core.util.RandomUtil;
import cn.stylefeng.guns.core.exception.BusinessException;
import cn.stylefeng.guns.dao.IGaiaProductBusinessService;
import cn.stylefeng.guns.dao.IGoodsService;
import cn.stylefeng.guns.dao.ISaleStockService;
import cn.stylefeng.guns.dao.entity.GaiaBatchInfo;
import cn.stylefeng.guns.dao.entity.Goods;
import cn.stylefeng.guns.dao.entity.SaleStock;
import cn.stylefeng.guns.dao.service.IGaiaBatchInfoService;
import cn.stylefeng.guns.modular.demo.enums.SaleStockTypeEnum;
import cn.stylefeng.guns.modular.demo.excel.domain.asilikang.WholesaleExcelVO;
import cn.stylefeng.guns.modular.demo.service.TestBizService;
import cn.stylefeng.guns.util.RebateDateUtil;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.exception.ExcelDataConvertException;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneOffset;
import java.time.temporal.TemporalAdjusters;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 阿斯利康采购数据
 */
@Slf4j
public class SaleAslikangListener implements ReadListener<WholesaleExcelVO> {


    /**
     * 每隔5条存储数据库，实际使用中可以100条，然后清理list ，方便内存回收
     */
    private static final int BATCH_COUNT = 100;
    private List<SaleStock> cachedDataList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    private List<String> keyList = ListUtils.newArrayListWithExpectedSize(BATCH_COUNT);
    /**
     * 假设这个是一个DAO，当然有业务逻辑这个也可以是一个service。当然如果不用存储这个对象没用。
     */
    private ISaleStockService saleStockService;

    private List<String> errorList;
    private IGoodsService goodsService;

    private TestBizService testBizService;
    private IGaiaBatchInfoService gaiaBatchInfoService;

    public SaleAslikangListener(ISaleStockService saleStockService, List<String> errorList, IGoodsService goodsService, TestBizService testBizService, IGaiaBatchInfoService gaiaBatchInfoService) {
        this.saleStockService = saleStockService;
        this.errorList = errorList;
        this.goodsService = goodsService;
        this.testBizService = testBizService;
        this.gaiaBatchInfoService = gaiaBatchInfoService;
    }

    /**
     * 这个每一条数据解析都会来调用
     *
     * @param data    one row value. It is same as {@link AnalysisContext#readRowHolder()}
     * @param context
     */
    @Override
    public void invoke(WholesaleExcelVO data, AnalysisContext context) {
        //w0crdxdq50ss
        log.info("解析到一条数据:{}", JSON.toJSONString(data));
        String billNo = data.getBillNo();
        String productCode = data.getProductCode();
        Date saleTime = data.getSaleTime();
        //批发销售数量
        Integer num = Math.abs(data.getNum());
        //批号
        String batch = data.getBatch();

        //4月份的放到5月份销售
        //5-6月份正常销售
        //6.5的两笔 8号前销售完
        //1.1
        Long time1 = 1704038400000L;
        Long time4 = 1711900800000L;
        Long time5 = 1714492800000L;
        Long time6 = 1717171200000L;
        long time = saleTime.getTime();
        List<GaiaBatchInfo> gaiaBatchInfoList = gaiaBatchInfoService.list(Wrappers.<GaiaBatchInfo>lambdaQuery().eq(GaiaBatchInfo::getBatBatchNo, batch)
                .eq(GaiaBatchInfo::getBatProCode, productCode));
        if (CollectionUtils.isEmpty(gaiaBatchInfoList)) {
            log.error("批号数据有问题,批号:{}", batch);
            return;
        }
        List<String> batBatchNoList = gaiaBatchInfoList.stream().map(GaiaBatchInfo::getBatBatchNo).collect(Collectors.toList());

        //  1-3 月份直接销售完
        if (time >= time1 && time < time4) {
            Goods goods = goodsService.getOne(Wrappers.<Goods>lambdaQuery().eq(Goods::getCommodityCode, productCode));
            if (Objects.isNull(goods)) {
                log.error("商品数据有问题,商品编码:{}", productCode);
            }
            //找到配送记录
            List<SaleStock> list = saleStockService.list(Wrappers.
                    <SaleStock>lambdaQuery()
                    .eq(SaleStock::getType, SaleStockTypeEnum.PD.getType())
                    .eq(SaleStock::getTag, "w0crdxdq50ss")
                    .eq(SaleStock::getGoodsId, productCode)
                    .eq(SaleStock::getBatch, batch)
            );
            list.stream().forEach(r -> {
                Integer calNum = r.getNum();
                for (String batBatchNo : batBatchNoList) {
                    //找到配送记录
                    long count = saleStockService.count(Wrappers.
                            <SaleStock>lambdaQuery()
                            .eq(SaleStock::getBatch, batBatchNo)
                            .eq(SaleStock::getType, SaleStockTypeEnum.LS.getType())
                            .eq(SaleStock::getGoodsId, productCode)
                            .eq(SaleStock::getTest, 0)
                            .groupBy(SaleStock::getStoCode)
                    );
                    if (count > 0) {
                        log.error("有销售记录 理论上就不是批发销售了batchNoList ={},productCode={},count={}", batBatchNoList, productCode, count);
                        //有销售记录 理论上就不是批发销售了
                        continue;
                    }

                    //随机天数时间
                    LocalDateTime localDateTime = LocalDateTime.of(LocalDate.now().plusDays(RandomUtil.randomInt(3, 4)), LocalTime.of(0, 0, 0));

                    LocalDateTime with = localDateTime.with(TemporalAdjusters.lastDayOfMonth());
                    //大于月末的时间取月末
                    Long epochMilli = null;
                    if (localDateTime.isBefore(with)) {
                        epochMilli = localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
                    } else {
                        epochMilli = with.toInstant(ZoneOffset.of("+8")).toEpochMilli();
                    }
                    testBizService.generateSingleSaleData(calNum, productCode, r.getStoCode(), batBatchNo, RebateDateUtil.format(epochMilli), "w0crdxdq50ss");
                }
            });
        } else if (time >= time4 && time < time5) {
            //4月份的放到5月份销售
            saleTime = new Date(time5);
        } else if (time >= time5 && time < time6) {
            //5-6月份正常销售
        } else {
            //6.5的两笔 8号前销售完
//            saleTime = new Date(1717929600000L);
        }


    }

    @Override
    public void onException(Exception exception, AnalysisContext context) {
        log.error("解析失败，但是继续解析下一行:{}", exception.getMessage());
        // 如果是某一个单元格的转换异常 能获取到具体行号
        // 如果要获取头的信息 配合invokeHeadMap使用
        if (exception instanceof ExcelDataConvertException) {
            ExcelDataConvertException excelDataConvertException = (ExcelDataConvertException) exception;
            log.error("第{}行，第{}列解析异常，数据为:{}", excelDataConvertException.getRowIndex(), excelDataConvertException.getColumnIndex(), excelDataConvertException.getCellData());
            errorList.add("第" + excelDataConvertException.getRowIndex() + "行，第" + excelDataConvertException.getColumnIndex() + "列解析异常，数据为:" + excelDataConvertException.getCellData());
        }

        if (exception instanceof BusinessException) {
            errorList.add(exception.getMessage());
        }

    }

    /**
     * 所有数据解析完成了 都会来调用
     *
     * @param context
     */
    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 这里也要保存数据，确保最后遗留的数据也存储到数据库
        saveData();
        log.info("所有数据解析完成！");
    }

    /**
     * 加上存储数据库
     */
    private void saveData() {
        log.info("{}条数据，开始存储数据库！", cachedDataList.size());
        saleStockService.saveBatch(cachedDataList);
        log.info("存储数据库成功！");
    }

}
